package com.yu.Demo02;

public class TestNotify {
    //实现线程直接通信
    private int num = 0;

    public synchronized void  incr () throws InterruptedException {
        while(num!=0){
            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName() + num);
        this.notifyAll();
    }

    public synchronized void decr() throws InterruptedException {
        if (num!=1){
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName() + num);
        this.notifyAll();

    }

    public static void main(String[] args) {
        TestNotify testNotify = new TestNotify();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    testNotify.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                try {
                    testNotify.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();



    }
}
